import time
import re
from common.pre_config_brower import chrome_brower, request_for_sales
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


class Very:
    def __init__(self, url):
        self.driver = chrome_brower(disableIMG=True, disableJS=True)
        self.home_url = url
        self.main_windows_id = None
        self.last_page = False
        self.open_web()

    #open the web pages
    def open_web(self):
        try:
            print(self.home_url)
            self.driver.get(self.home_url)
            self.main_windows_id = self.driver.window_handles[-1]
        except Exception as e:
            print("open the first page failure", e)

    # search the elements, e.g. production name , href, picture and so on
    def get_info_from_page(self):
        # self.roll_to_top()
        self.driver.implicitly_wait(30)
        # time.sleep(10000)
        
        while True:
            items_num_info_list = self.driver.find_elements_by_xpath('//li[@class="product"]')
            items_num_per_page = len(items_num_info_list)
            print(items_num_per_page)
            if items_num_per_page == 99 or self.last_page:
                break
            else:
                self.open_web()
                self.roll_to_top()

        for item in items_num_info_list:
            produce_url_pic_name_elment = item.find_element_by_xpath('div[@class="productImages"]/a')
            produce_url = produce_url_pic_name_elment.get_attribute('href')
            produce_pic_name_elment = produce_url_pic_name_elment.find_element_by_xpath('img')
            jpg_url = produce_pic_name_elment.get_attribute('src')
            produce_name = produce_pic_name_elment.get_attribute('alt')

            price_value = item.find_element_by_xpath('div[@class="productInfo"]//a[@class="productPrice"]').text
            yield jpg_url, produce_name, price_value, produce_url

    def roll_to_top(self, interval=500):
        index = 0
        while index < 18000:
            js = "var q=document.documentElement.scrollTop=%s" % index
            self.driver.execute_script(js)
            time.sleep(1)
            index += interval

    def get_all_items(self):
        items_total_element = self.driver.find_element_by_css_selector('[class="productsPerPage"] > span').text
        items_total_num = int(re.search(r".*?\(of (\d+)\)", items_total_element).group(1))
        total_page_num = items_total_num // 99
        if items_total_num % 99:
            total_page_num += 1
        print(items_total_num, total_page_num)

        page_url = self.home_url
        windows_id_list = list()
        for page_num in range(1, total_page_num+1):
            self.home_url = page_url
            self.home_url += "&pageNumber=%s" % page_num
            print(self.home_url)
            windows_id_list.append(self.open_url_in_new_window(self.home_url))
            if page_num == total_page_num:
                self.last_page = True

            if (page_num+1) % 10 == 0 or self.last_page:
                for win_id in windows_id_list:
                    self.driver.switch_to_window(win_id)
                    if page_num + 1 == total_page_num and win_id == windows_id_list[-1]:
                        self.last_page = True
                    for infor in self.get_info_from_page():
                        yield infor
                    self.driver.close()
                windows_id_list.clear()
                self.driver.switch_to_window(self.driver.window_handles[0])

    def open_url_in_new_window(self, url):
        js = "window.open('%s')" % url
        self.driver.execute_script(js)
        return self.driver.window_handles[-1]
